package com.investmenttechnologyservices.services;

import java.util.logging.Logger;

import com.google.appengine.api.datastore.DatastoreService;
import com.google.appengine.api.datastore.EntityNotFoundException;
import com.google.appengine.api.datastore.Key;
import com.google.appengine.api.datastore.Transaction;
import com.google.inject.Inject;
import com.investmenttechnologyservices.model.Firm;


public class FirmServiceImpl implements FirmService {
	
	private static final Logger log = Logger.getLogger(FirmServiceImpl.class.getName());
	
	private final DatastoreService ds;
	
	@Inject
	FirmServiceImpl(DatastoreService ds) {
		this.ds = ds;
	}

	public Long getNextTradeId(Key accountKey) {
		log.info("[getNextTradeId(in): accountKey="+accountKey.toString()+"]");

		Key firmKey = accountKey.getParent();
		Firm myFirm = null;
		
		Long nextTradeId = null;
		try {
			myFirm = new Firm(ds.get(firmKey));
			nextTradeId =myFirm.getNextTradeId();
			myFirm.setNextTradeId(nextTradeId+1L);

			Transaction tx = ds.beginTransaction();
			ds.put(myFirm.asEntity());
			tx.commit();
		} catch (EntityNotFoundException ex) {
			log.severe("Could not get next trade from firm.");
		} catch (IllegalStateException ex) {
			log.severe("commit failed!!!");
		}
		
		try {
			int count=0;
			myFirm = new Firm(ds.get(firmKey));
			while (myFirm.getNextTradeId() < (nextTradeId+1L) &&
				count < 5) {
				log.info("[getnextTradeId(2): not updated="+count+"]");
				try {
					Thread.sleep(1000);
				} catch (InterruptedException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
				myFirm = new Firm(ds.get(firmKey));
			}
		} catch (EntityNotFoundException ex) {
			ex.printStackTrace();
		}
		log.info("[getNextTradeId(out): nextTradeId="+nextTradeId+
				"\tStored next="+((myFirm!=null)?myFirm.getNextTradeId():" problem!")+"]");
		return nextTradeId;

	}
	
}
